import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk'

import {ListProp} from '../types/list.d';

interface Istate{
    list:ListProp[]
}

let reducer = (state:Istate={list:[]},action:any) => {
    switch (action.type) {
        case 'initlist':
            return {...state,list:[...action.list]}
        case 'changeNum':
            // parentIndex :类型的index  id:指定商品的id status:加还是减
            let {parentIndex,id,status} = action;

            let index = state.list[parentIndex].children.findIndex(item => item.id==id);

            if(status === '+'){
                //加
                state.list[parentIndex].children[index].num++;
                state.list[parentIndex].num++;
            }else{
                //减
                if( state.list[parentIndex].children[index].num > 0){
                    state.list[parentIndex].children[index].num--;
                }
               
                state.list[parentIndex].num--;
            }

            return {...state,list:[...state.list]}
        default:
            return state;
    }
}   

let store = createStore(reducer,applyMiddleware(thunk));

export default store